package com.ews.onlineexchange.endpoint;

import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

import javax.ejb.Lock;
import javax.ejb.LockType;
import javax.inject.Singleton;
import javax.websocket.Session;

@Singleton
public class SessionRegistry {
	
	private final Map<String, Set<Session>> sessions = new HashMap<>();

	@Lock(LockType.READ)
	public Set<Session> getAll(String bulletinId) {
		synchronized (sessions) {
			if(sessions.isEmpty()) {
				return null;
			}
			
			Set<Session> bulletinSession = sessions.get(bulletinId);
			if(bulletinSession == null || bulletinSession.size() == 0 ) return null;
			return Collections.unmodifiableSet(bulletinSession);
		}
		
	}

	@Lock(LockType.WRITE)
	public void add(Session session) {
		synchronized (sessions) {
			String bulletinId = session.getPathParameters().get("bulletinId");
			if (sessions.get(bulletinId) == null)
				sessions.put(bulletinId, new HashSet<>());
			sessions.get(bulletinId).add(session);
		}
		
	}

	@Lock(LockType.WRITE)
	public void remove(Session session) {
		synchronized(sessions){
			String bulletinId = session.getPathParameters().get("bulletinId");
			if (sessions.get(bulletinId) == null)
				sessions.put(bulletinId, new HashSet<>());
			sessions.get(bulletinId).remove(session);
		}
		
	}
}